import React, { Component } from 'react';
import { Form, Input, Select, Button, Checkbox, Radio } from 'antd';
import Utils from './../../utils/utils';
const FormItem = Form.Item;

class BaseForm extends Component {
	
	//最新版本使用此方法创建ref
	formRef = React.createRef();
	
	//form表单提交
	onFinish = () => {
		//获取表单的值
		let formValues = this.formRef.current.getFieldsValue();
		//将表单数据传回给父组件，在父组件进行提交后台
		this.props.updateSubmit(formValues);
	}
	
	//清空form表单
	onReset = () => {
		this.formRef.current.resetFields();
	};
	
	//点击不同项，Form表单重新赋值
	UNSAFE_componentWillReceiveProps(nextProps){
		this.formRef.current.setFieldsValue(nextProps.selectedItem);
	}
	
	//第一次对Form表单赋值有效，只作用第一次
	componentDidMount(){
		let selectedItem = this.props.selectedItem;
		this.formRef.current.setFieldsValue(selectedItem);
	}
	
	//根据父组件传过来的值初始化表单有哪些项
	initFormList = ()=>{
		//父组件传过来表单有哪些项
		const formList = this.props.formList;
		//用于存放遍历好的Form.Item项
		let formItemList = [];
		if(formList && formList.length > 0){
			formList.forEach((item,index)=>{
				let label = item.label;//Form.Item标题
				let field = item.field;//唯一标识
				let placeholder = item.placeholder;//提示
				if(item.type === "INPUT"){
					const INPUT = 
					<FormItem
						key={field}
						label={label}
						name={field}
					>
						<Input type="text" placeholder={placeholder} />
					</FormItem>
					formItemList.push(INPUT);
				}else if(item.type === "PASSWORD"){
					const INPUT1 = 
					<FormItem
						key={field}
						label={label}
						name={field}
					>
						<Input.Password type="text" placeholder={placeholder} />
					</FormItem>
					formItemList.push(INPUT1);
				}else if(item.type === "SELECT"){
					const SELECT = 
					<FormItem
						key={field}
						label={label}
						name={field}
					>
						<Select placeholder={placeholder}>
							{ Utils.getOptionList(item.list) }
						</Select>
					</FormItem>
					formItemList.push(SELECT);
				}else if(item.type === "CHECKBOX"){
					const CHECKBOX = 
					<FormItem
						key={field}
						label={label}
						name={field}
						valuePropName= 'checked'
					>
						<Checkbox>
							
						</Checkbox>
					</FormItem>
					formItemList.push(CHECKBOX);
				}else if(item.type === "RADIO"){
					const RADIO = 
					<FormItem
						key={field}
						label={label}
						name={field}
					>
						<Radio.Group>
							{Utils.getRadioList(item.list)}
						</Radio.Group>
					</FormItem>
					formItemList.push(RADIO);
				}
			})
		}
		return formItemList;
	}
	render(){
		const layout = {
		    labelCol: { span: 6 },
		    wrapperCol: { span: 18 },
		};
		const tailLayout = {
			wrapperCol: {
				offset: 6,
				span: 18,
			},
		};
		return (
			<Form
				{...layout}
				ref={this.formRef}
				onFinish={this.onFinish}
			>
				{this.initFormList()}
				<FormItem {...tailLayout}>
					<Button type="primary" htmlType="submit">保存</Button>
					<Button onClick={this.onReset}>重置</Button>
				</FormItem>
			</Form>
		)
	}
}

export default BaseForm;